package com.fieldchain.ex.fa100.ui.market.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.Constant;
import com.fieldchain.ex.fa100.bean.User;
import com.fieldchain.ex.fa100.bean.event.MainEvent;
import com.fieldchain.ex.fa100.bean.MarketBean;
import com.fieldchain.ex.fa100.inter.SimpleCallBack;
import com.fieldchain.ex.fa100.ui.kline.KLineActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import com.fieldchain.ex.fa100.utils.chart.mk_chart.MarketChart;
import com.fieldchain.ex.fa100.utils.net.access.HttpRequest;
import com.fieldchain.ex.fa100.utils.net.modle.StringRequest;
import com.fieldchain.ex.fa100.utils.screen.MyToast;
import com.fieldchain.ex.fa100.utils.share.ShareManager;
import com.fieldchain.ex.fa100.utils.string.NumberFormate;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/13
 */
public class MarketAdapter extends RecyclerView.Adapter<MarketAdapter.ViewHolder> {
    private Context mContext;
    private Drawable d1, d2, d3, d4;
    private int c1, c2;
    private List<MarketBean> list = new ArrayList<>();
    private boolean[] tags;
    private String[] strMethod = {"getMarket", "getVolume", "getRecentQuotation", "getChange"};

    private int oldindex=-1, newindex=-1;
    private String market = "";
    private int moneyType = 0;
    private Drawable draw;

    public MarketAdapter(Context mContext) {
        this.mContext = mContext;
        draw=ContextCompat.getDrawable(mContext, R.drawable.shape_mk);
        d1 = mContext.getResources().getDrawable(R.drawable.icon_mkup);
        d2 = mContext.getResources().getDrawable(R.drawable.icon_mkdown);
        d3 = mContext.getResources().getDrawable(R.drawable.shape_content12_30);
        d4 = mContext.getResources().getDrawable(R.drawable.shape_content12_30_2);
        c1 = Color.parseColor("#FFDC3950");
        c2 = Color.parseColor("#FF00B05F");
    }


    public void clear() {
        market="";
        tags = new boolean[list.size()];
        oldindex = newindex = -1;
    }

    public void setData(List<MarketBean> list) {
        User user=ShareManager.getInstance().getUser();
        if (user==null|| user.getAssistantCurrency()==2) {
            moneyType = 0;
        } else {
            moneyType = 1;
        }
        this.list = list;
        if (tags != null && tags.length == list.size()) {

        } else {
            tags = new boolean[list.size()];
        }
        notifyDataSetChanged();
    }

    public List<MarketBean> getData() {
        return list;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_market, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final MarketBean bean = list.get(position);
        final boolean hadCollect = bean.getCollect() == 1;
        if (bean.getChange() >= 0) {
            holder.ivStatus.setBackground(d1);
            holder.tvPer.setTextColor(c1);
        } else {
            holder.ivStatus.setBackground(d2);
            holder.tvPer.setTextColor(c2);
        }

        if (hadCollect) {
            holder.cbIv.setChecked(true);
            holder.cbTv.setChecked(true);
        } else {
            holder.cbIv.setChecked(false);
            holder.cbTv.setChecked(false);
        }

        holder.tvPer.setText(bean.getChange() + "%");
        holder.tvCompany1.setText(bean.getMarket().replace("_", "/").toUpperCase());
        holder.tvNum.setText(bean.getVolume() + "");
        if (tags[position]) {
            holder.mkchart.setValues( draw,getChartData(bean.getTendency()));
            holder.linBottom.setVisibility(View.VISIBLE);
            holder.linTop.setBackground(d4);
        } else {
            holder.linBottom.setVisibility(View.GONE);
            holder.linTop.setBackground(d3);
        }

        holder.tvPrice.setText(bean.getRecentQuotation() + "");

        holder.linTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newindex = position;
                tags[newindex] = !tags[newindex];
                if (oldindex != newindex && oldindex >= 0) {
                    tags[oldindex] = false;
                }

                if (tags[newindex]) {
                    market = bean.getMarket();
                    if (oldindex >= 0) notifyItemChanged(oldindex);
                } else {
                    market = "";
                }
                notifyItemChanged(newindex);
                oldindex = newindex;
            }
        });

        holder.linCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                collect(bean.getMarket(), new SimpleCallBack() {
                    @Override
                    public void sure() {
                        if (bean.getCollect() == 1) {
                            bean.setCollect(0);
                            holder.cbIv.setChecked(false);
                            holder.cbTv.setChecked(false);
                        } else {
                            bean.setCollect(1);
                            holder.cbIv.setChecked(true);
                            holder.cbTv.setChecked(true);
                        }
                    }
                });
            }
        });

        holder.linExchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().post(new MainEvent(1, 0, bean.getMarket()));
            }
        });

        holder.linBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mContext, KLineActivity.class);
                intent.putExtra("market",bean.getMarket().toLowerCase());
//                intent.putExtra("type",1);
                mContext.startActivity(intent);
//                ((Activity) mContext).finish();
            }
        });

        if (moneyType == 0) {
            holder.tvCompany2.setText("¥");
            String price = NumberFormate.m(bean.getDealRatioCny() * bean.getRecentQuotation()+"",5,false);
            holder.tvPrice.setText(price);
        } else {
            holder.tvCompany2.setText("＄");
            String price = NumberFormate.m(bean.getDealRatioUsd() * bean.getRecentQuotation()+"",5,false);
            holder.tvPrice.setText(price);
        }


    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private LinearLayout linTop;
        private ImageView ivStatus;
        private TextView tvCompany1;
        private TextView tvNum;
        private TextView tvPer;
        private TextView tvPrice;
        private TextView tvCompany2;
        private LinearLayout linBottom;
        private MarketChart mkchart;
        private LinearLayout linCollect;
        private CheckBox cbIv;
        private CheckBox cbTv;
        private LinearLayout linExchange;

        public ViewHolder(View itemView) {
            super(itemView);
            linTop = itemView.findViewById(R.id.lin_top);
            ivStatus = itemView.findViewById(R.id.iv_status);
            tvCompany1 = itemView.findViewById(R.id.tv_company1);
            tvNum = itemView.findViewById(R.id.tv_num);
            tvPer = itemView.findViewById(R.id.tv_per);
            tvPrice = itemView.findViewById(R.id.tv_price);
            tvCompany2 = itemView.findViewById(R.id.tv_company2);
            linBottom = itemView.findViewById(R.id.lin_bottom);
            mkchart = itemView.findViewById(R.id.mkchart);
            linCollect = itemView.findViewById(R.id.lin_collect);
            cbIv = itemView.findViewById(R.id.cb_iv);
            cbTv = itemView.findViewById(R.id.cb_tv);
            linExchange = itemView.findViewById(R.id.lin_exchange);
        }
    }


    public List<List<String>> getChartData(String tendency) {
        List<List<String>> list = new Gson().fromJson(tendency, new TypeToken<List<List<String>>>() {}.getType());
        Collections.reverse(list);
        return list;
    }


    public void collect(String market, final SimpleCallBack callBack) {
        HashMap map = new HashMap();
        map.put("market", market);
        HttpRequest.getInstance().postRequest( map, Constant.collect,new StringRequest() {
            @Override
            public void onSucess(String str, int code, String msg) {
                if (code == 200) {
                    callBack.sure();
                }
                if(code==403){
                    if(ShareManager.getInstance().getUser()==null) {
                        MyToast.show("未登录");
                    }else{
                        MyToast.show("登录过期");
                    }
                }else {
                    MyToast.show(msg);
                }

            }

            @Override
            public void onFaild(Exception e) {

            }
        });
    }

    public void sort(int type, int index) {
        Log.e("type_mk66:",index+"");
        listSort(list, strMethod[type], index);
        tags=new boolean[list.size()];
        for(int i=0;i<list.size();i++){
            if(list.get(i).getMarket().equals(market)){
                tags[i]=true;
            }
        }
        notifyDataSetChanged();
    }

    private void listSort(List<MarketBean> list, final String method, final int sort) {
        Log.e("type_mk55:",sort+"");
        Collections.sort(list, new MarketCompare(method, sort));
    }
}
